<template>
  <div class="users-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1>用户管理</h1>
      <div class="header-tabs">
        <el-tabs v-model="activeTab" @tab-change="handleTabChange">
          <el-tab-pane label="用户列表" name="users"></el-tab-pane>
          <el-tab-pane label="用户组管理" name="groups"></el-tab-pane>
          <el-tab-pane label="用户角色管理" name="roles"></el-tab-pane>
          <el-tab-pane label="权限管理" name="permissions"></el-tab-pane>
        </el-tabs>
      </div>
    </div>

    <!-- 用户列表 -->
    <div v-show="activeTab === 'users'" class="tab-content">
      <div class="toolbar">
        <el-button type="primary" @click="showAddUserDialog">
          <i class="fa fa-plus"></i> 添加用户
        </el-button>
        <el-button @click="refreshUsers">
          <i class="fa fa-refresh"></i> 刷新
        </el-button>
        <div class="search-box">
          <el-input v-model="searchText" placeholder="搜索用户..." clearable>
            <template #prefix>
              <i class="fa fa-search"></i>
            </template>
          </el-input>
        </div>
      </div>

      <el-table :data="filteredUsers" style="width: 100%" v-loading="loading">
        <el-table-column prop="id" label="ID" width="60" />
        <el-table-column prop="username" label="用户名" min-width="120" />
        <el-table-column prop="email" label="邮箱" min-width="180" />
        <el-table-column prop="chinese_name" label="中文名" min-width="100" />
        <el-table-column label="用户组" min-width="150">
          <template #default="scope">
            <el-tag v-for="group in scope.row.groups" :key="group.id" size="small" style="margin-right: 5px;">
              {{ group.name }}
            </el-tag>
            <span v-if="!scope.row.groups || scope.row.groups.length === 0" class="text-muted">未分配</span>
          </template>
        </el-table-column>
        <el-table-column prop="is_active" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.is_active ? 'success' : 'danger'" size="small">
              {{ scope.row.is_active ? '激活' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="last_login" label="最后登录" min-width="160">
          <template #default="scope">
            {{ formatDateTime(scope.row.last_login) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="280" fixed="right">
          <template #default="scope">
            <div class="action-buttons">
              <el-tooltip content="查看用户详情" placement="top">
                <el-button size="small" type="primary" circle @click="viewUser(scope.row)">
                  <i class="fa fa-eye"></i>
                </el-button>
              </el-tooltip>
              <el-tooltip content="编辑用户信息" placement="top">
                <el-button size="small" type="warning" circle @click="editUser(scope.row)">
                  <i class="fa fa-edit"></i>
                </el-button>
              </el-tooltip>
              <el-tooltip content="管理用户组" placement="top">
                <el-button size="small" type="info" circle @click="manageUserGroups(scope.row)">
                  <i class="fa fa-users"></i>
                </el-button>
              </el-tooltip>
              <el-tooltip content="切换用户状态" placement="top">
                <el-button
                  size="small"
                  :type="scope.row.is_active ? 'success' : 'danger'"
                  circle
                  @click="toggleUserStatus(scope.row)"
                >
                  <i :class="scope.row.is_active ? 'fa fa-check' : 'fa fa-ban'"></i>
                </el-button>
              </el-tooltip>
              <el-tooltip content="删除用户" placement="top">
                <el-button size="small" type="danger" circle @click="deleteUser(scope.row)">
                  <i class="fa fa-trash"></i>
                </el-button>
              </el-tooltip>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 用户组管理 -->
    <div v-show="activeTab === 'groups'" class="tab-content">
      <div class="toolbar">
        <el-button type="primary" @click="showAddGroupDialog">
          <i class="fa fa-plus"></i> 添加用户组
        </el-button>
        <el-button @click="refreshGroups">
          <i class="fa fa-refresh"></i> 刷新
        </el-button>
      </div>

      <el-table :data="userGroups" style="width: 100%" v-loading="groupsLoading">
        <el-table-column prop="id" label="ID" width="60" />
        <el-table-column prop="name" label="组名" min-width="150" />
        <el-table-column prop="code" label="组代码" min-width="120" />
        <el-table-column prop="description" label="描述" min-width="200" />
        <el-table-column label="用户数量" width="100">
          <template #default="scope">
            <el-tag size="small">{{ scope.row.user_count || 0 }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="created_at" label="创建时间" min-width="160">
          <template #default="scope">
            {{ formatDateTime(scope.row.created_at) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button size="small" type="primary" @click="viewGroupUsers(scope.row)">
              成员
            </el-button>
            <el-button size="small" type="warning" @click="editGroup(scope.row)">
              编辑
            </el-button>
            <el-button size="small" type="danger" @click="deleteGroup(scope.row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 用户角色管理 -->
    <div v-show="activeTab === 'roles'" class="tab-content">
      <div class="toolbar">
        <el-button type="primary" @click="showAddRoleDialog">
          <i class="fa fa-plus"></i> 添加用户角色
        </el-button>
        <el-button @click="refreshRoles">
          <i class="fa fa-refresh"></i> 刷新
        </el-button>
        <div class="filter-box">
          <el-select v-model="selectedGroupFilter" placeholder="按用户组筛选" clearable @change="filterRolesByGroup">
            <el-option label="全部" value="" />
            <el-option v-for="group in userGroups" :key="group.id" :label="group.name" :value="group.id" />
          </el-select>
        </div>
      </div>

      <el-table :data="filteredRoles" style="width: 100%" v-loading="rolesLoading">
        <el-table-column prop="id" label="ID" width="60" />
        <el-table-column prop="name" label="角色名" min-width="150" />
        <el-table-column prop="group_name" label="所属用户组" min-width="120" />
        <el-table-column prop="level_display" label="权限级别" width="100">
          <template #default="scope">
            <el-tag :type="getRoleLevelType(scope.row.level)" size="small">
              {{ scope.row.level_display }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="description" label="描述" min-width="200" />
        <el-table-column prop="created_at" label="创建时间" min-width="160">
          <template #default="scope">
            {{ formatDateTime(scope.row.created_at) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button size="small" type="primary" @click="viewRoleUsers(scope.row)">
              用户
            </el-button>
            <el-button size="small" type="warning" @click="editRole(scope.row)">
              编辑
            </el-button>
            <el-button size="small" type="danger" @click="deleteRole(scope.row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 权限管理 -->
    <div v-show="activeTab === 'permissions'" class="tab-content">
      <div class="toolbar">
        <el-button type="primary" @click="showPermissionDialog">
          <i class="fa fa-cog"></i> 配置权限
        </el-button>
        <el-button @click="refreshPermissions">
          <i class="fa fa-refresh"></i> 刷新
        </el-button>
      </div>

      <el-card>
        <template #header>
          <span>菜单权限配置</span>
        </template>
        <div class="permission-config">
          <el-row :gutter="20">
            <el-col :span="8">
              <h4>用户组列表</h4>
              <el-tree
                :data="groupTreeData"
                node-key="id"
                :props="{ label: 'name', children: 'children' }"
                @node-click="selectGroupForPermission"
                highlight-current
              />
            </el-col>
            <el-col :span="16">
              <h4>菜单权限 <span v-if="selectedPermissionGroup">({{ selectedPermissionGroup.name }})</span></h4>
              <div v-if="selectedPermissionGroup">
                <el-tree
                  ref="permissionTreeRef"
                  :data="menuTreeData"
                  node-key="id"
                  show-checkbox
                  :props="{ label: 'title', children: 'children' }"
                  :default-checked-keys="groupPermissions"
                  @check="handlePermissionChange"
                />
                <div style="margin-top: 20px;">
                  <el-button type="primary" @click="saveGroupPermissions">
                    保存权限
                  </el-button>
                </div>
              </div>
              <div v-else class="empty-state">
                <p>请选择一个用户组来配置权限</p>
              </div>
            </el-col>
          </el-row>
        </div>
      </el-card>
    </div>

    <!-- 添加用户对话框 -->
    <el-dialog v-model="showUserDialog" title="添加用户" width="600px">
      <el-form :model="userForm" :rules="userRules" ref="userFormRef" label-width="100px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="userForm.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="userForm.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="中文名" prop="chinese_name">
          <el-input v-model="userForm.chinese_name" placeholder="请输入中文名" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="userForm.password" type="password" placeholder="请输入密码" />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input v-model="userForm.confirmPassword" type="password" placeholder="请确认密码" />
        </el-form-item>
        <el-form-item label="状态">
          <el-switch v-model="userForm.is_active" active-text="激活" inactive-text="禁用" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showUserDialog = false">取消</el-button>
          <el-button type="primary" @click="submitUserForm">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 编辑用户对话框 -->
    <el-dialog v-model="showEditUserDialog" title="编辑用户" width="600px">
      <el-form :model="userForm" :rules="editUserRules" ref="userFormRef" label-width="100px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="userForm.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="userForm.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="中文名" prop="chinese_name">
          <el-input v-model="userForm.chinese_name" placeholder="请输入中文名" />
        </el-form-item>
        <el-form-item label="新密码" prop="password">
          <el-input v-model="userForm.password" type="password" placeholder="留空则不修改密码" />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword" v-if="userForm.password">
          <el-input v-model="userForm.confirmPassword" type="password" placeholder="请确认密码" />
        </el-form-item>
        <el-form-item label="状态">
          <el-switch v-model="userForm.is_active" active-text="激活" inactive-text="禁用" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showEditUserDialog = false">取消</el-button>
          <el-button type="primary" @click="submitEditUserForm">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 用户组分配对话框 -->
    <el-dialog v-model="showUserGroupDialog" title="管理用户组" width="600px">
      <el-form :model="userGroupForm" label-width="100px">
        <el-form-item label="用户">
          <span>{{ currentEditUser?.username }}</span>
        </el-form-item>
        <el-form-item label="用户组">
          <el-select v-model="userGroupForm.group_ids" multiple placeholder="请选择用户组">
            <el-option
              v-for="group in userGroups"
              :key="group.id"
              :label="group.name"
              :value="group.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="角色">
          <el-select v-model="userGroupForm.role_ids" multiple placeholder="请选择角色">
            <el-option
              v-for="role in userRoles"
              :key="role.id"
              :label="role.name"
              :value="role.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showUserGroupDialog = false">取消</el-button>
          <el-button type="primary" @click="submitUserGroupForm">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 添加用户组对话框 -->
    <el-dialog v-model="showGroupDialog" title="添加用户组" width="500px">
      <el-form :model="groupForm" :rules="groupRules" ref="groupFormRef" label-width="100px">
        <el-form-item label="组名" prop="name">
          <el-input v-model="groupForm.name" placeholder="请输入组名" />
        </el-form-item>
        <el-form-item label="组代码" prop="code">
          <el-input v-model="groupForm.code" placeholder="请输入组代码" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="groupForm.description" type="textarea" placeholder="请输入描述" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showGroupDialog = false">取消</el-button>
          <el-button type="primary" @click="submitGroupForm">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 添加用户角色对话框 -->
    <el-dialog v-model="showRoleDialog" title="添加用户角色" width="500px">
      <el-form :model="roleForm" :rules="roleRules" ref="roleFormRef" label-width="100px">
        <el-form-item label="角色名" prop="name">
          <el-input v-model="roleForm.name" placeholder="请输入角色名" />
        </el-form-item>
        <el-form-item label="所属用户组" prop="group">
          <el-select v-model="roleForm.group" placeholder="请选择用户组">
            <el-option v-for="group in userGroups" :key="group.id" :label="group.name" :value="group.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="权限级别" prop="level">
          <el-select v-model="roleForm.level" placeholder="请选择权限级别">
            <el-option label="超级管理员" :value="1" />
            <el-option label="管理员" :value="2" />
            <el-option label="普通用户" :value="3" />
          </el-select>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="roleForm.description" type="textarea" placeholder="请输入描述" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showRoleDialog = false">取消</el-button>
          <el-button type="primary" @click="submitRoleForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, nextTick } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, ElMessageBox, ElTree } from 'element-plus'
import axios from 'axios'

const router = useRouter()
const route = useRoute()

// 标签页状态
const activeTab = ref('users')

// 根据路由参数设置默认标签页
const initializeTab = () => {
  const defaultTab = route.meta?.defaultTab
  if (defaultTab) {
    activeTab.value = defaultTab
    console.log('根据路由meta设置标签页:', defaultTab)
  } else {
    // 根据路由路径判断
    const path = route.path
    if (path.includes('/user/groups')) {
      activeTab.value = 'groups'
      console.log('根据路径设置标签页: groups')
    } else if (path.includes('/user/roles')) {
      activeTab.value = 'roles'
      console.log('根据路径设置标签页: roles')
    } else {
      activeTab.value = 'users'
      console.log('默认设置标签页: users')
    }
  }

  // 立即加载对应标签页的数据
  console.log('initializeTab 加载数据，当前标签页:', activeTab.value)
  loadTabData(activeTab.value)
}

// 用户相关状态
const loading = ref(false)
const searchText = ref('')
const users = ref([])

// 用户组相关状态
const groupsLoading = ref(false)
const userGroups = ref([])

// 用户角色相关状态
const rolesLoading = ref(false)
const userRoles = ref([])
const selectedGroupFilter = ref('')

// 权限相关状态
const selectedPermissionGroup = ref(null)
const groupPermissions = ref([])
const menuTreeData = ref([])
const permissionTreeRef = ref<InstanceType<typeof ElTree>>()

// 对话框状态
const showUserDialog = ref(false)
const showEditUserDialog = ref(false)
const showUserGroupDialog = ref(false)
const showGroupDialog = ref(false)
const showRoleDialog = ref(false)
const isEditMode = ref(false)
const currentEditUser = ref(null)

// 表单数据
const userForm = ref({
  username: '',
  email: '',
  chinese_name: '',
  password: '',
  confirmPassword: '',
  is_active: true
})

const groupForm = ref({
  name: '',
  code: '',
  description: ''
})

const roleForm = ref({
  name: '',
  group: '',
  level: 3,
  description: ''
})

const userGroupForm = ref({
  user_id: '',
  group_ids: [],
  role_ids: []
})

// 表单引用
const userFormRef = ref()
const groupFormRef = ref()
const roleFormRef = ref()

// 表单验证规则
const userRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    {
      validator: (rule: any, value: any, callback: any) => {
        if (value !== userForm.value.password) {
          callback(new Error('两次输入密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

const groupRules = {
  name: [
    { required: true, message: '请输入组名', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入组代码', trigger: 'blur' }
  ]
}

const roleRules = {
  name: [
    { required: true, message: '请输入角色名', trigger: 'blur' }
  ],
  group: [
    { required: true, message: '请选择用户组', trigger: 'change' }
  ],
  level: [
    { required: true, message: '请选择权限级别', trigger: 'change' }
  ]
}

const editUserRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  password: [
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
  ],
  confirmPassword: [
    {
      validator: (rule: any, value: any, callback: any) => {
        if (userForm.value.password && value !== userForm.value.password) {
          callback(new Error('两次输入密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 计算属性
const filteredUsers = computed(() => {
  // 确保users.value是数组
  if (!Array.isArray(users.value)) {
    console.warn('users.value不是数组:', users.value)
    return []
  }

  if (!searchText.value) return users.value
  return users.value.filter(user =>
    user.username?.toLowerCase().includes(searchText.value.toLowerCase()) ||
    user.email?.toLowerCase().includes(searchText.value.toLowerCase()) ||
    user.chinese_name?.includes(searchText.value) ||
    user.first_name?.includes(searchText.value)
  )
})

const filteredRoles = computed(() => {
  if (!selectedGroupFilter.value) return userRoles.value
  return userRoles.value.filter(role => role.group == selectedGroupFilter.value)
})

const groupTreeData = computed(() => {
  return userGroups.value.map(group => ({
    id: group.id,
    name: group.name,
    children: []
  }))
})

// 工具函数
const formatDateTime = (dateTime: string) => {
  if (!dateTime) return '从未'
  return new Date(dateTime).toLocaleString('zh-CN')
}

const getRoleLevelType = (level: number) => {
  switch (level) {
    case 1: return 'danger'   // 超级管理员
    case 2: return 'warning'  // 管理员
    case 3: return 'info'     // 普通用户
    default: return ''
  }
}

// 标签页切换
const handleTabChange = (tabName: string) => {
  console.log('标签页切换到:', tabName)
  // 保存当前标签页到localStorage
  localStorage.setItem('userManagementActiveTab', tabName)

  // 加载对应标签页的数据
  loadTabData(tabName)
}

// 加载标签页数据
const loadTabData = (tabName: string) => {
  console.log('🚀 loadTabData 被调用，标签页:', tabName)
  try {
    switch (tabName) {
      case 'users':
        console.log('📋 加载用户数据...')
        fetchUsers()
        break
      case 'groups':
        console.log('👥 加载用户组数据...')
        fetchUserGroups()
        break
      case 'roles':
        console.log('🏷️ 加载角色数据...')
        fetchUserRoles()
        fetchUserGroups() // 角色需要用户组数据
        break
      case 'permissions':
        console.log('🔐 加载权限数据...')
        fetchUserGroups()
        fetchMenus()
        break
      default:
        console.warn('⚠️ 未知的标签页:', tabName)
    }
  } catch (error) {
    console.error('❌ loadTabData 执行失败:', error)
  }
}

// 用户管理函数
const showAddUserDialog = () => {
  userForm.value = {
    username: '',
    email: '',
    chinese_name: '',
    password: '',
    confirmPassword: '',
    is_active: true
  }
  showUserDialog.value = true
}

const submitUserForm = async () => {
  try {
    await userFormRef.value.validate()

    const userData = {
      username: userForm.value.username,
      email: userForm.value.email,
      chinese_name: userForm.value.chinese_name,
      is_active: userForm.value.is_active
    }

    // 只有在密码不为空时才包含密码字段
    if (userForm.value.password) {
      userData.password = userForm.value.password
    }

    await axios.post('/api/users/', userData)
    ElMessage.success('用户创建成功')
    showUserDialog.value = false
    fetchUsers()
  } catch (error) {
    console.error('创建用户失败:', error)
    ElMessage.error('创建用户失败')
  }
}

const submitEditUserForm = async () => {
  try {
    await userFormRef.value.validate()

    const userData = {
      username: userForm.value.username,
      email: userForm.value.email,
      chinese_name: userForm.value.chinese_name,
      is_active: userForm.value.is_active
    }

    // 只有在密码不为空时才包含密码字段
    if (userForm.value.password) {
      userData.password = userForm.value.password
    }

    await axios.patch(`/api/users/${currentEditUser.value.id}/`, userData)
    ElMessage.success('用户更新成功')
    showEditUserDialog.value = false
    isEditMode.value = false
    currentEditUser.value = null
    fetchUsers()
  } catch (error) {
    console.error('更新用户失败:', error)
    ElMessage.error('更新用户失败')
  }
}

const refreshUsers = () => {
  fetchUsers()
}

const viewUser = (user: any) => {
  router.push(`/users/detail/${user.id}`)
}

const editUser = (user: any) => {
  currentEditUser.value = user
  userForm.value = {
    username: user.username,
    email: user.email,
    chinese_name: user.chinese_name || '',
    password: '',
    confirmPassword: '',
    is_active: user.is_active
  }
  isEditMode.value = true
  showEditUserDialog.value = true
}

const manageUserGroups = async (user: any) => {
  currentEditUser.value = user
  userGroupForm.value.user_id = user.id

  // 获取用户当前的组和角色
  try {
    const response = await axios.get(`/api/users/${user.id}/groups/`)
    userGroupForm.value.group_ids = response.data.groups || []
    userGroupForm.value.role_ids = response.data.roles || []
  } catch (error) {
    console.error('获取用户组信息失败:', error)
    userGroupForm.value.group_ids = []
    userGroupForm.value.role_ids = []
  }

  showUserGroupDialog.value = true
}

const toggleUserStatus = async (user: any) => {
  try {
    const newStatus = !user.is_active
    await axios.patch(`/api/users/${user.id}/`, { is_active: newStatus })
    user.is_active = newStatus
    ElMessage.success(`用户已${newStatus ? '激活' : '禁用'}`)
  } catch (error) {
    console.error('切换用户状态失败:', error)
    ElMessage.error('切换用户状态失败')
  }
}

const deleteUser = async (user: any) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除用户 "${user.username}" 吗？此操作不可恢复。`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )

    await axios.delete(`/api/users/${user.id}/`)
    ElMessage.success('用户删除成功')
    fetchUsers()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除用户失败:', error)
      ElMessage.error('删除用户失败')
    }
  }
}

const submitUserGroupForm = async () => {
  try {
    await axios.post(`/api/users/${userGroupForm.value.user_id}/assign_groups/`, {
      group_ids: userGroupForm.value.group_ids,
      role_ids: userGroupForm.value.role_ids
    })
    ElMessage.success('用户组分配成功')
    showUserGroupDialog.value = false
    fetchUsers()
  } catch (error) {
    console.error('分配用户组失败:', error)
    ElMessage.error('分配用户组失败')
  }
}

const fetchUsers = async () => {
  console.log('🔄 开始获取用户列表...')
  loading.value = true
  try {
    console.log('📡 发送API请求: GET /api/users/')
    const response = await axios.get('/api/users/')
    console.log('✅ 用户API响应:', response.data)

    // 处理分页格式的响应数据
    if (response.data && response.data.results && Array.isArray(response.data.results)) {
      users.value = response.data.results
      console.log('📊 设置用户数据(分页格式):', response.data.results.length, '条')
    } else if (Array.isArray(response.data)) {
      users.value = response.data
      console.log('📊 设置用户数据(直接数组):', response.data.length, '条')
    } else {
      console.error('❌ API返回的数据格式不正确:', response.data)
      users.value = []
    }
  } catch (error) {
    console.error('❌ 获取用户列表失败:', error)
    ElMessage.error('获取用户列表失败')
    users.value = []
  } finally {
    loading.value = false
    console.log('✅ 用户数据获取完成，最终数据:', users.value)
  }
}

// 用户组管理函数
const showAddGroupDialog = () => {
  groupForm.value = {
    name: '',
    code: '',
    description: ''
  }
  showGroupDialog.value = true
}

const submitGroupForm = async () => {
  try {
    await groupFormRef.value.validate()

    await axios.post('/api/usergroups/', groupForm.value)
    ElMessage.success('用户组创建成功')
    showGroupDialog.value = false
    fetchUserGroups()
  } catch (error) {
    console.error('创建用户组失败:', error)
    ElMessage.error('创建用户组失败')
  }
}

const refreshGroups = () => {
  fetchUserGroups()
}

const viewGroupUsers = (group: any) => {
  ElMessage.info(`查看组成员功能开发中: ${group.name}`)
}

const editGroup = (group: any) => {
  ElMessage.info(`编辑用户组功能开发中: ${group.name}`)
}

const deleteGroup = async (group: any) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除用户组 "${group.name}" 吗？此操作不可恢复。`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )

    await axios.delete(`/api/usergroups/${group.id}/`)
    ElMessage.success('用户组删除成功')
    fetchUserGroups()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除用户组失败:', error)
      ElMessage.error('删除用户组失败')
    }
  }
}

const fetchUserGroups = async () => {
  console.log('开始获取用户组数据...')
  groupsLoading.value = true
  try {
    const response = await axios.get('/api/usergroups/')
    console.log('用户组API响应:', response.data)

    // 处理分页格式的响应数据
    if (response.data && response.data.results && Array.isArray(response.data.results)) {
      userGroups.value = response.data.results
      console.log('设置用户组数据:', response.data.results.length, '条')
    } else if (Array.isArray(response.data)) {
      userGroups.value = response.data
      console.log('设置用户组数据(直接数组):', response.data.length, '条')
    } else {
      console.error('用户组API返回的数据格式不正确:', response.data)
      userGroups.value = []
    }
  } catch (error) {
    console.error('获取用户组列表失败:', error)
    ElMessage.error('获取用户组列表失败')
    userGroups.value = []
  } finally {
    groupsLoading.value = false
    console.log('用户组数据获取完成，最终数据:', userGroups.value)
  }
}

// 用户角色管理函数
const showAddRoleDialog = () => {
  roleForm.value = {
    name: '',
    group: '',
    level: 3,
    description: ''
  }
  showRoleDialog.value = true
}

const submitRoleForm = async () => {
  try {
    await roleFormRef.value.validate()

    await axios.post('/api/userroles/', roleForm.value)
    ElMessage.success('用户角色创建成功')
    showRoleDialog.value = false
    fetchUserRoles()
  } catch (error) {
    console.error('创建用户角色失败:', error)
    ElMessage.error('创建用户角色失败')
  }
}

const refreshRoles = () => {
  fetchUserRoles()
}

const filterRolesByGroup = () => {
  // 过滤逻辑在computed中处理
}

const viewRoleUsers = (role: any) => {
  ElMessage.info(`查看角色用户功能开发中: ${role.name}`)
}

const editRole = (role: any) => {
  ElMessage.info(`编辑用户角色功能开发中: ${role.name}`)
}

const deleteRole = async (role: any) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除用户角色 "${role.name}" 吗？此操作不可恢复。`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )

    await axios.delete(`/api/userroles/${role.id}/`)
    ElMessage.success('用户角色删除成功')
    fetchUserRoles()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除用户角色失败:', error)
      ElMessage.error('删除用户角色失败')
    }
  }
}

const fetchUserRoles = async () => {
  rolesLoading.value = true
  try {
    const response = await axios.get('/api/userroles/')

    // 处理分页格式的响应数据
    if (response.data && response.data.results && Array.isArray(response.data.results)) {
      userRoles.value = response.data.results
    } else if (Array.isArray(response.data)) {
      userRoles.value = response.data
    } else {
      console.error('用户角色API返回的数据格式不正确:', response.data)
      userRoles.value = []
    }
  } catch (error) {
    console.error('获取用户角色列表失败:', error)
    ElMessage.error('获取用户角色列表失败')
    userRoles.value = []
  } finally {
    rolesLoading.value = false
  }
}

// 权限管理函数
const showPermissionDialog = () => {
  ElMessage.info('权限配置功能开发中')
}

const refreshPermissions = () => {
  fetchUserGroups()
  fetchMenus()
}

const selectGroupForPermission = (group: any) => {
  selectedPermissionGroup.value = group
  fetchGroupPermissions(group.id)
}

const handlePermissionChange = () => {
  // 权限变更处理
}

const saveGroupPermissions = async () => {
  if (!selectedPermissionGroup.value) return

  try {
    const checkedKeys = permissionTreeRef.value?.getCheckedKeys() || []
    await axios.post('/api/menupermissions/set_group_permissions/', {
      group_id: selectedPermissionGroup.value.id,
      menu_ids: checkedKeys
    })
    ElMessage.success('权限保存成功')
  } catch (error) {
    console.error('保存权限失败:', error)
    ElMessage.error('保存权限失败')
  }
}

const fetchGroupPermissions = async (groupId: number) => {
  try {
    const response = await axios.get(`/api/menupermissions/get_group_permissions/?group_id=${groupId}`)
    groupPermissions.value = response.data.map((p: any) => p.menu)
  } catch (error) {
    console.error('获取组权限失败:', error)
    groupPermissions.value = []
  }
}

const fetchMenus = async () => {
  try {
    const response = await axios.get('/api/menus/')

    // 处理分页格式的响应数据
    let menuData = []
    if (response.data && response.data.results && Array.isArray(response.data.results)) {
      menuData = response.data.results
    } else if (Array.isArray(response.data)) {
      menuData = response.data
    } else {
      console.error('菜单API返回的数据格式不正确:', response.data)
      menuData = []
    }

    menuTreeData.value = buildMenuTree(menuData)
  } catch (error) {
    console.error('获取菜单列表失败:', error)
    menuTreeData.value = []
  }
}

const buildMenuTree = (menus: any[]) => {
  const menuMap = new Map()
  const roots: any[] = []

  // 创建菜单映射
  menus.forEach(menu => {
    menuMap.set(menu.id, { ...menu, children: [] })
  })

  // 构建树结构
  menus.forEach(menu => {
    const menuNode = menuMap.get(menu.id)
    if (menu.parent) {
      const parent = menuMap.get(menu.parent)
      if (parent) {
        parent.children.push(menuNode)
      }
    } else {
      roots.push(menuNode)
    }
  })

  return roots
}

// 初始化
onMounted(async () => {
  console.log('🎯 用户管理页面 onMounted 开始执行')
  console.log('📍 当前路由路径:', route.path)
  console.log('📍 当前路由meta:', route.meta)
  console.log('📍 当前路由name:', route.name)

  // 首先根据路由参数设置标签页并加载数据
  if (route.meta?.defaultTab || route.path.includes('/user/')) {
    console.log('✅ 检测到路由参数，使用 initializeTab')
    // 有路由参数，使用 initializeTab 设置标签页并加载数据
    initializeTab()
  } else {
    console.log('⚠️ 没有路由参数，从localStorage恢复')
    // 没有路由参数，从localStorage恢复标签页状态
    const savedTab = localStorage.getItem('userManagementActiveTab')
    console.log('从localStorage获取的标签页:', savedTab)

    if (savedTab && ['users', 'groups', 'roles', 'permissions'].includes(savedTab)) {
      activeTab.value = savedTab
      console.log('设置activeTab为:', savedTab)
    }

    // 等待DOM更新
    await nextTick()

    // 加载当前标签页的数据
    console.log('开始加载数据，当前标签页:', activeTab.value)
    loadTabData(activeTab.value)
  }

  console.log('🎯 用户管理页面 onMounted 执行完成')
})
</script>

<style lang="scss" scoped>
.users-container {
  padding: 20px;
  background: linear-gradient(135deg, #0f1327 0%, #1a2332 50%, #0f1327 100%);
  min-height: 100vh;
  color: #e6e6e6;
}

.page-header {
  margin-bottom: 30px;

  h1 {
    color: #8b5cf6;
    margin-bottom: 20px;
    text-shadow: 0 0 10px rgba(139, 92, 246, 0.5);
    font-size: 32px;
    font-weight: 700;
  }

  .header-tabs {
    :deep(.el-tabs__header) {
      margin: 0;
      border-bottom: 2px solid rgba(139, 92, 246, 0.3);
    }

    :deep(.el-tabs__nav-wrap::after) {
      display: none;
    }

    :deep(.el-tabs__item) {
      color: #8892b0;
      font-weight: 500;

      &.is-active {
        color: #8b5cf6;
      }

      &:hover {
        color: #8b5cf6;
      }
    }

    :deep(.el-tabs__active-bar) {
      background-color: #8b5cf6;
    }
  }
}

.tab-content {
  .toolbar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding: 15px 20px;
    background: rgba(139, 92, 246, 0.1);
    border-radius: 10px;
    border: 1px solid rgba(139, 92, 246, 0.3);

    .search-box, .filter-box {
      width: 300px;
    }
  }

  :deep(.el-table) {
    background: rgba(15, 23, 42, 0.9);
    border: 1px solid rgba(139, 92, 246, 0.3);
    border-radius: 10px;

    .el-table__header {
      background: rgba(139, 92, 246, 0.2);

      th {
        background: transparent;
        color: #8b5cf6;
        font-weight: 600;
        border-bottom: 1px solid rgba(139, 92, 246, 0.3);
      }
    }

    .el-table__body {
      tr {
        background: transparent;

        &:hover {
          background: rgba(139, 92, 246, 0.1);
        }

        td {
          border-bottom: 1px solid rgba(139, 92, 246, 0.1);
          color: #e6e6e6;
        }
      }
    }
  }

  :deep(.el-button) {
    border-radius: 6px;
    font-weight: 500;

    &.el-button--primary {
      background: linear-gradient(135deg, #8b5cf6, #6366f1);
      border: none;

      &:hover {
        background: linear-gradient(135deg, #7c3aed, #5b21b6);
      }
    }

    &.el-button--warning {
      background: linear-gradient(135deg, #f59e0b, #d97706);
      border: none;

      &:hover {
        background: linear-gradient(135deg, #d97706, #b45309);
      }
    }

    &.el-button--danger {
      background: linear-gradient(135deg, #ef4444, #dc2626);
      border: none;

      &:hover {
        background: linear-gradient(135deg, #dc2626, #b91c1c);
      }
    }
  }
}

.permission-config {
  .empty-state {
    text-align: center;
    padding: 40px;
    color: #8892b0;

    p {
      font-size: 16px;
    }
  }

  h4 {
    color: #8b5cf6;
    margin-bottom: 15px;
    font-weight: 600;
  }

  :deep(.el-tree) {
    background: transparent;
    color: #e6e6e6;

    .el-tree-node__content {
      &:hover {
        background: rgba(139, 92, 246, 0.1);
      }
    }

    .el-tree-node.is-current > .el-tree-node__content {
      background: rgba(139, 92, 246, 0.2);
      color: #8b5cf6;
    }
  }
}

:deep(.el-card) {
  background: rgba(15, 23, 42, 0.9);
  border: 1px solid rgba(139, 92, 246, 0.3);
  border-radius: 10px;

  .el-card__header {
    background: rgba(139, 92, 246, 0.1);
    border-bottom: 1px solid rgba(139, 92, 246, 0.3);
    color: #8b5cf6;
    font-weight: 600;
  }

  .el-card__body {
    background: transparent;
  }
}

:deep(.el-input) {
  .el-input__wrapper {
    background: rgba(15, 23, 42, 0.8);
    border: 1px solid rgba(139, 92, 246, 0.3);
    border-radius: 6px;

    &:hover {
      border-color: rgba(139, 92, 246, 0.5);
    }

    &.is-focus {
      border-color: #8b5cf6;
      box-shadow: 0 0 0 2px rgba(139, 92, 246, 0.2);
    }
  }

  .el-input__inner {
    color: #e6e6e6;

    &::placeholder {
      color: #8892b0;
    }
  }
}

:deep(.el-select) {
  .el-input__wrapper {
    background: rgba(15, 23, 42, 0.8);
    border: 1px solid rgba(139, 92, 246, 0.3);
  }
}

:deep(.el-tag) {
  border-radius: 4px;
  font-weight: 500;
}

.text-muted {
  color: #8892b0;
  font-style: italic;
}

.action-buttons {
  display: flex;
  gap: 8px;
  align-items: center;
  justify-content: center;

  .el-button {
    width: 32px;
    height: 32px;
    padding: 0;
    display: flex;
    align-items: center;
    justify-content: center;
    transition: all 0.3s ease;

    i {
      font-size: 14px;
    }

    &.el-button--primary {
      background: linear-gradient(135deg, #3b82f6, #1d4ed8);
      border: none;

      &:hover {
        background: linear-gradient(135deg, #2563eb, #1e40af);
        transform: translateY(-1px);
        box-shadow: 0 4px 12px rgba(59, 130, 246, 0.4);
      }
    }

    &.el-button--warning {
      background: linear-gradient(135deg, #f59e0b, #d97706);
      border: none;

      &:hover {
        background: linear-gradient(135deg, #d97706, #b45309);
        transform: translateY(-1px);
        box-shadow: 0 4px 12px rgba(245, 158, 11, 0.4);
      }
    }

    &.el-button--info {
      background: linear-gradient(135deg, #6b7280, #4b5563);
      border: none;

      &:hover {
        background: linear-gradient(135deg, #4b5563, #374151);
        transform: translateY(-1px);
        box-shadow: 0 4px 12px rgba(107, 114, 128, 0.4);
      }
    }

    &.el-button--success {
      background: linear-gradient(135deg, #10b981, #059669);
      border: none;

      &:hover {
        background: linear-gradient(135deg, #059669, #047857);
        transform: translateY(-1px);
        box-shadow: 0 4px 12px rgba(16, 185, 129, 0.4);
      }
    }

    &.el-button--danger {
      background: linear-gradient(135deg, #ef4444, #dc2626);
      border: none;

      &:hover {
        background: linear-gradient(135deg, #dc2626, #b91c1c);
        transform: translateY(-1px);
        box-shadow: 0 4px 12px rgba(239, 68, 68, 0.4);
      }
    }
  }
}
</style>
